package top.xcxdl.rural.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.log4j.Log4j2;
import top.xcxdl.rural.entity.BackAdmin;
import top.xcxdl.rural.mapper.BackAdminMapper;
import top.xcxdl.rural.service.IBackAdminService;
import org.springframework.stereotype.Service;
import top.xcxdl.rural.utils.JWTUtils;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Ding
 * @since 2022-01-27
 */
@Log4j2
@Service
public class BackAdminServiceImpl extends ServiceImpl<BackAdminMapper, BackAdmin> implements IBackAdminService {

    @Resource
    private BackAdminMapper mapper;

    @Override
    public BackAdmin toLogin(String username, String password) {
        QueryWrapper<BackAdmin> wrapper = new QueryWrapper<>();
        wrapper.eq("a_username",username);
        wrapper.eq("a_password",password);
        return mapper.selectOne(wrapper);
    }

    @Override
    public PageInfo<BackAdmin> getList(Integer page_no, Integer page_size,String title) {
        PageHelper.startPage(page_no,page_size);
        return new PageInfo<>(mapper.getList(title));
    }

    @Override
    public int doEdit(BackAdmin bean) {
        if (bean.getAId() == null){
            //添加
            bean.setAPassword(bean.getAUsername());
            bean.setAStatus(1);
            bean.setACreateTime(String.valueOf(System.currentTimeMillis()/1000));
            return mapper.insert(bean);
        }else{
            //编辑
            QueryWrapper<BackAdmin> wrapper = new QueryWrapper<>();
            wrapper.eq("a_id",bean.getAId());
            return mapper.update(bean,wrapper) + 1;
        }
    }

    @Override
    public int getByUsername(String aUsername) {
        //编辑
        QueryWrapper<BackAdmin> wrapper = new QueryWrapper<>();
        wrapper.eq("a_username",aUsername);
        return mapper.selectCount(wrapper);
    }

    @Override
    public int doDeleteBy(List<Integer> ids) {
        QueryWrapper<BackAdmin> wrapper = new QueryWrapper<>();
        wrapper.in("a_id",ids);
        int ret = mapper.delete(wrapper);
        if(ret > 0 ){
            log.info("管理员{}（ID为{}）：删除了{}个管理员，id为：{}", JWTUtils.getAuthorName(), JWTUtils.getAuthorId(),ids.size(),ids);
        }
        return ret;
    }

    @Override
    public BackAdmin getAdminUserById(Integer id) {
        return mapper.getAdminUserById(id);
    }
}
